package com.dingreading.cloud.common.util.aliyun;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;

import java.util.HashMap;
import java.util.Map;

public class GetObjectProgressListener implements ProgressListener {

    public GetObjectProgressListener(String taskId) {
        this.taskId = taskId;
    }

    //已经存好的数据长度
    private long bytesWritten = 0;
    //下载的数据总长度
    private long totalBytes = -1;
    //下载的当前进度,例如50时，代表下载进度为50%
    private int percent = 0;
    //是否下载完成, 0.未完成 1.已完成 -1.失败
    private int succeed = 0;
    //数据在oss中的objectName，也相当于任务ID
    private String taskId = "";

    public int getPercent() {
        return percent;
    }

    public int getSucceed() {
        return succeed;
    }

    //用来存储所有下载任务进度
    public static Map<String, GetObjectProgressListener> progressBarMap = new HashMap<>();

    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                //响应开始下载事件
                //保存下载任务
                progressBarMap.put(taskId, this);
//                System.out.println("开始下载，taskId = " + taskId);
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                //响应下载的字节长度事件
                this.totalBytes = bytes;
//                System.out.println("响应下载的字节长度事件");
//                System.out.println("bytes in total will be downloaded to a local file：" + this.totalBytes);
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                //响应字节转换事件
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    this.percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
//                    System.out.println(bytes + " bytes have been written at this time, upload progress: " +
//                            percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                } else {
//                    System.out.println(bytes + " bytes have been written at this time, upload ratio: unknown" +
//                            "(" + this.bytesWritten + "/...)");
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                //下载完成事件
                this.succeed = 1;
//                System.out.println("下载完成， " + this.bytesWritten);
                break;
            case TRANSFER_FAILED_EVENT:
                //下载失败事件
                this.succeed = -1;
//                System.out.println("下载失败， " + this.bytesWritten);
                break;
            default:
                break;
        }
    }

}
